package cn.wildfire.chat.app.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.InterfaceReceiversHub;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.wxapi.WXUserInfo;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.wildfire.chat.app.extendsion.classes.BindPhoneRequest;
import cn.wildfire.chat.app.extendsion.classes.BindUserInfo;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.classes.SendCodeRequest;
import cn.wildfire.chat.app.extendsion.classes.UserCheckRequest;
import cn.wildfire.chat.app.extendsion.classes.ViewTimerSet;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.login.model.LoginResult;
import cn.wildfire.chat.app.main.CountrySetActivity;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.app.main.RegisterActivity;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.net.OKHttpHelper;
import cn.wildfire.chat.kit.net.SimpleCallback;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

/**
 * Create by HEKE, 2019/8/12 18:58
 * TODO 短信登入界面
 */
public class SMSLoginActivity extends WfcBaseActivity {

    @BindView(R2.id.loginButton)
    Button loginButton;
    @BindView(R2.id.phoneNumberEditText)
    EditText phoneNumberEditText;
    @BindView(R2.id.authCodeEditText)
    EditText authCodeEditText;
    @BindView(R2.id.requestAuthCodeButton)
    TextView requestAuthCodeButton;
    @BindView(R2.id.countrySelector)
    TextView countrySelector;
    @BindView(R2.id.selectedCountryTxt)
    TextView selectedCountryTxt;
    @BindView(R2.id.registerTxt)
    TextView registerTxt;
    @BindView(R2.id.registerMsgLayout)
    LinearLayout registerMsgLayout;
    @BindView(R2.id.bindPhoneMsgTxt)
    TextView bindPhoneMsgTxt;
    @BindView(R2.id.currentMobileTxt)
    TextView currentMobileTxt;
    @BindView(R2.id.exhcangePhoneLayout)
    FrameLayout exhcangePhoneLayout;

    private String phoneNumber;

    private Region currentRegion;

    /**
     * 来自于微信登入绑定手机号
     */
    protected WXUserInfo wxUserInfo;

    /**
     * 来自于账号与安全绑定手机号
     */
    protected UserInfo userInfo;
    protected String phone;
    protected boolean haveBindPhone;

    private void initViews() {
        // 获取登入界面传入国家区号信息
        Intent intent = getIntent();
        Region getRegion = null;
        if (intent != null) {
            getRegion = intent.getParcelableExtra("Region");
        }
        if (getRegion == null) {
            currentRegion = new Region(438, "86", getString(R.string.default_country));
        } else {
            currentRegion = getRegion;
        }
        selectedCountryTxt.setText(currentRegion.regionName);
        // 微信绑定手机号操作
        wxUserInfo = intent.getParcelableExtra("wxUserInfo");
        if (wxUserInfo != null) {
            wxUserInfo.setRegionId("" + currentRegion.id);
        }
        userInfo = intent.getParcelableExtra("userInfo");
        haveBindPhone = intent.getBooleanExtra("havaBindPhone", false);
        phone = intent.getStringExtra("phone");
        // 初次微信登入绑定手机号
        if (wxUserInfo != null) {
            setReplaceTitle(null, R.string.bind_phone_number_title);
            loginButton.setText(R.string.confirm_btn);
            bindPhoneMsgTxt.setVisibility(View.VISIBLE);
            bindPhoneMsgTxt.setText(R.string.bind_phone_msg_content);
            registerMsgLayout.setVisibility(View.GONE);
        } else {
            // 账号与安全中心绑定手机号
            if (userInfo != null) {
                if (haveBindPhone) {
                    setReplaceTitle(null, R.string.exchange_bind_phone_number);
                    loginButton.setText(R.string.confirm_btn);
                    bindPhoneMsgTxt.setVisibility(View.VISIBLE);
                    bindPhoneMsgTxt.setText(R.string.exchange_bind_phone_msg_content);
                    exhcangePhoneLayout.setVisibility(View.VISIBLE);
                    currentMobileTxt.setText("" + phone);
                } else {
                    setReplaceTitle(null, R.string.bind_phone_number_title);
                    loginButton.setText(R.string.confirm_btn);
                    bindPhoneMsgTxt.setVisibility(View.VISIBLE);
                    bindPhoneMsgTxt.setText(R.string.bind_phone_msg_content);
                }
                registerMsgLayout.setVisibility(View.GONE);
            }
            // 短信登录
            else {
                loginButton.setText(R.string.login_title);
                bindPhoneMsgTxt.setVisibility(View.GONE);
                registerMsgLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected int contentLayout() {
        return R.layout.login_activity_sms;
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setSearchLayoutVisibility(false);
        initViews();
    }

    @OnTextChanged(value = R2.id.phoneNumberEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputPhoneNumber(Editable editable) {
        String phone = editable.toString().trim();
        if (phone.length() >= 6) {
            requestAuthCodeButton.setEnabled(true);
        } else {
            requestAuthCodeButton.setEnabled(false);
            loginButton.setEnabled(false);
        }
    }

    @OnTextChanged(value = R2.id.authCodeEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputAuthCode(Editable editable) {
        if (editable.toString().length() > 2) {
            loginButton.setEnabled(true);
        }
    }

    @OnClick(R2.id.loginButton)
    void login() {
        String phoneNumber = phoneNumberEditText.getText().toString().trim();
        String authCode = authCodeEditText.getText().toString().trim();
        if (TextUtils.isTextEmpty(phoneNumber) || TextUtils.isTextEmpty(authCode)) {
            return;
        }
        // 微信绑定手机号请求
        if (wxUserInfo != null) {
            wxUserInfo.regionId = "" + currentRegion.id;
            wxUserInfo.code = authCode;
            wxUserInfo.mobile = phoneNumber;
            Intent bind = new Intent();
            bind.putExtra("wxUserInfo", wxUserInfo);
            setResult(Activity.RESULT_OK, bind);
            finish();
        } else {
            // 账号与安全中心
            if (userInfo != null) {
                if (phone != null && phoneNumber.equals(phone)) {
                    ToastTip.tip(getString(R.string.please_input_new_phone_number));
                    return;
                }
                if (phoneNumber.length() < 6) {
                    ToastTip.tip(getString(R.string.phone_number_error));
                    return;
                }
                new BindPhoneRequest(this, phoneNumber, userInfo.uid, "" + currentRegion.id, authCode,
                        new BindPhoneRequest.OnBindPhoneListener() {
                            @Override
                            public void bindPhone(boolean success, BindUserInfo bindUserInfo, String message) {
                                if (success) {
                                    ToastTip.tip(getString(R.string.bind_phone_success));
                                    Intent toExchangePhoneIntent = new Intent();
                                    toExchangePhoneIntent.putExtra("bind_result", success);
                                    setResult(Activity.RESULT_OK, toExchangePhoneIntent);
                                    finish();
                                } else {
                                    ToastTip.tip("" + message);
                                }
                            }
                        });
            }
            // 短信登录
            else {
                String url = ServerUrlClient.CODE_LOGIN;
                Map<String, String> params = new HashMap<>();
                try {
                    params.put("clientId", ChatManagerHolder.gChatManager.getClientId());
                    params.put("mobile", phoneNumber);
                    params.put("code", authCode);
                    params.put("regionId", "" + currentRegion.id);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastTip.tip(getString(R.string.network_not_valid));
                    return;
                }

                MaterialDialog dialog = new MaterialDialog.Builder(this)
                        .content(getString(R.string.logining_msg))
                        .progress(true, 100)
                        .cancelable(false)
                        .build();
                dialog.show();
                OKHttpHelper.post(url, params, new SimpleCallback<LoginResult>() {
                    @SuppressLint("ApplySharedPref")
                    @Override
                    public void onUiSuccess(LoginResult loginResult) {
                        if (isFinishing()) {
                            return;
                        }
                        dialog.dismiss();
                        ChatManagerHolder.gChatManager.connect(loginResult.getUserId(), loginResult.getToken());
                        SPUtils.setMuches(SMSLoginActivity.this, "config",
                                new String[]{"id", "token"}, new String[]{loginResult.getUserId(), loginResult.getToken()});
                        ChatManager.Instance().getUserInfo(loginResult.getUserId(), true);
                        Intent intent = new Intent(SMSLoginActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        // 注册推送账号
                        InterfaceReceiversHub.setMiPushAccount(SMSLoginActivity.this, loginResult.getUserId());
                        // 注册设备账号
                        finish();
                    }

                    @Override
                    public void onUiFailure(int code, String msg) {
                        if (isFinishing()) {
                            return;
                        }
                        Toast.makeText(SMSLoginActivity.this, getString(R.string.login_failure) + ":" + code + " " + msg, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
            }
        }
    }

    protected boolean requestCodeLock;

    @OnClick(R2.id.requestAuthCodeButton)
    void requestAuthCode() {
        phoneNumber = phoneNumberEditText.getText().toString();
        if (TextUtils.isTextEmpty(phoneNumber)) {
            ToastTip.tip(getString(R.string.phone_hint));
            return;
        }
        // 账号与安全中心
        if (userInfo != null) {
            if (haveBindPhone && phoneNumber.equals(userInfo.mobile)) {
                ToastTip.tip(getString(R.string.please_input_new_phone_number));
                return;
            }
        }
        if (!requestCodeLock) {
            if (viewTimerSet != null && !viewTimerSet.isTimeoutFinished()) {
                return;
            }
            requestCodeLock = true;
            if (userInfo != null) {
                exchangeBindPhone();
            } else {
                smsCheckPhone();
            }
        }
    }

    protected ViewTimerSet viewTimerSet;

    /**
     * 更换绑定手机
     */
    private void exchangeBindPhone() {
        try {
            viewTimerSet = new ViewTimerSet(SMSLoginActivity.this, requestAuthCodeButton);
            viewTimerSet.run();
            new SendCodeRequest(SMSLoginActivity.this, phoneNumber, "" + currentRegion.id, new SendCodeRequest.OnSendCodeListener() {
                @Override
                public void send(boolean success) {
                    requestCodeLock = false;
                    if (!success) {
                        viewTimerSet.forceInterrupt();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 只进行手机绑定
     */
    private void smsCheckPhone() {
        try {
            new UserCheckRequest(this, phoneNumber, new UserCheckRequest.OnUserCheckResultListener() {
                @Override
                public void result(boolean existed) {
                    requestCodeLock = false;
                    if (existed) {
                        viewTimerSet = new ViewTimerSet(SMSLoginActivity.this, requestAuthCodeButton);
                        viewTimerSet.run();
                        new SendCodeRequest(SMSLoginActivity.this, phoneNumber, "" + currentRegion.id, new SendCodeRequest.OnSendCodeListener() {
                            @Override
                            public void send(boolean success) {
                                if (!success) {
                                    viewTimerSet.forceInterrupt();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(SMSLoginActivity.this, getString(R.string.user_not_found_register), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R2.id.countrySelector)
    public void onViewClicked() {
        Intent intent = new Intent(SMSLoginActivity.this, CountrySetActivity.class);
        intent.putExtra("RegionList", ((CaiBaChatApp) getApplicationContext()).regionFetcher.getmRegionRet());
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调选择国家编码
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            Region currentRegion = data.getParcelableExtra("mRegion");
            if (currentRegion != null) {
                SMSLoginActivity.this.currentRegion = currentRegion;
                selectedCountryTxt.setText(currentRegion.regionName);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R2.id.registerTxt})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.registerTxt) {
            Intent toRegister = new Intent(SMSLoginActivity.this, RegisterActivity.class);
            toRegister.putExtra("Region", currentRegion);
            startActivity(toRegister);
        }
    }

    @Override
    public void onBackPressed() {
        try {
            if (wxUserInfo != null) {
                Intent bind = new Intent();
                bind.putExtra("wxUserInfo", wxUserInfo);
                setResult(Activity.RESULT_CANCELED, bind);
            } else {
                if (userInfo != null) {
                    Intent bind = new Intent();
                    setResult(Activity.RESULT_CANCELED, bind);
                }
            }
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
